package com.demo.arch.datapulsedemo.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 模拟订单数据访问器
 * 模拟从数据库查询数据
 * 
 * @author DataPulse Team
 */
@Slf4j
@Component
public class MockOrderMapper {

  /**
   * 根据报表类型查询订单数据
   */
  public List<OrderData> selectByReportType(String reportType) {
    log.debug("MockOrderMapper: 查询{}数据", reportType);

    // 模拟数据库查询耗时
    simulateDbQuery();

    // 根据报表类型确定数据量
    int dataCount = determineDataCount(reportType);

    // 生成模拟数据
    List<OrderData> orders = new ArrayList<>();
    for (int i = 1; i <= dataCount; i++) {
      orders.add(generateOrderData(i));
    }

    log.debug("MockOrderMapper: 查询完成，返回{}条数据", orders.size());
    return orders;
  }

  /**
   * 根据报表类型确定数据量
   */
  private int determineDataCount(String reportType) {
    return switch (reportType) {
      case "日报" -> 20;
      case "周报" -> 100;
      case "月报" -> 500;
      case "年报" -> 2000;
      default -> 50;
    };
  }

  /**
   * 生成单条订单数据
   */
  private OrderData generateOrderData(int index) {
    String[] companies = {
        "阿里巴巴", "腾讯科技", "百度在线", "京东商城", "美团网络",
        "字节跳动", "滴滴出行", "小米科技", "华为技术", "网易公司"
    };

    String[] statuses = { "已完成", "进行中", "已取消" };

    return OrderData.builder()
        .orderNo("ORD" + String.format("%06d", index))
        .customerName(companies[index % companies.length] + "有限公司")
        .amount(BigDecimal.valueOf(1000 + (index * 123.45) % 49000).setScale(2, java.math.RoundingMode.HALF_UP))
        .orderTime(LocalDateTime.now().minusDays(index))
        .status(statuses[index % statuses.length])
        .build();
  }

  /**
   * 模拟数据库查询延迟
   */
  private void simulateDbQuery() {
    try {
      Thread.sleep(100);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }
  }
}
